package com.heima.wemedia.auto;

import okhttp3.*;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.json.JSONObject;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.concurrent.TimeUnit;

/**
 * TODO
 *
 * @Author mr.Du
 * @Date 2025/6/27 2025/6/27
 */
@Component
public class AutoCheck {


    // 百度AI开放平台的API Key，用于获取访问令牌（Access Token）
    public static final String API_KEY = "BvtM8SjE8gCHUNGFpUPKe8Ct";

    // 百度AI开放平台的Secret Key，用于身份验证和生成访问令牌
    public static final String SECRET_KEY = "3PMMAazxujFmtAROUnMKwmQXrxZT1Lzf";

    // 创建OkHttpClient实例，并设置读取超时时间为300秒
    public static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder()
            .readTimeout(300, TimeUnit.SECONDS)
            .build();

    /**
     * 百度云文本审核接口
     *
     * @return
     */
    public static String checkText(String content) {
        // 定义请求体的媒体类型为application/x-www-form-urlencoded
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");

        // 构建空的请求体
        RequestBody body = RequestBody.create(mediaType, content);
        String conclusion = null;

        try {
            // 构建POST请求对象，目标URL为百度文本审核接口，并携带访问令牌
            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token=" + getAccessToken())
                    .method("POST", body)
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .addHeader("Accept", "application/json")
                    .build();

            // 发送HTTP请求并获取响应
            Response response = HTTP_CLIENT.newCall(request).execute();
            String string = null;

            // 处理响应结果
            string = response.body().string();

            JSONObject jsonObject = new JSONObject(string);
            conclusion = jsonObject.getString("conclusion");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return conclusion;
    }

    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        // 定义请求体的媒体类型为application/x-www-form-urlencoded
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");

        // 构建请求体，包含获取Access Token所需的参数
        RequestBody body = RequestBody.create(mediaType,
                "grant_type=client_credentials&client_id=" + API_KEY
                        + "&client_secret=" + SECRET_KEY);

        // 构建POST请求对象，目标URL为百度OAuth接口
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();

        // 发送HTTP请求并获取响应
        Response response = HTTP_CLIENT.newCall(request).execute();

        // 解析JSON响应并返回Access Token
        return new JSONObject(response.body().string()).getString("access_token");
    }

    /**
     * 百度云图片审核接口
     * @param image
     * @return
     */
    public static String CheckImage(String image) {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        // image 可以通过 getFileContentAsBase64("C:\fakepath\ComfyUI_00001_.png") 方法获取,如果Content-Type是application/x-www-form-urlencoded时,第二个参数传true
        String string = null;
        try {
            String base64 = getFileContentAsBase64(image, true);
            RequestBody body = RequestBody.create(mediaType, "image="+base64);
            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined?access_token=" + getAccessToken())
                    .method("POST", body)
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .addHeader("Accept", "application/json")
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            string = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = new JSONObject(string);
        String conclusion = jsonObject.getString("conclusion");
        return conclusion;
    }

    static String getFileContentAsBase64(String path, boolean urlEncode) throws IOException {
        byte[] b;
        if (path.startsWith("http://") || path.startsWith("https://")) {
            // 处理远程URL
            URL url = new URL(path);
            try (InputStream in = url.openStream()) {
                ByteArrayOutputStream buffer = new ByteArrayOutputStream();
                int nRead;
                byte[] data = new byte[1024];
                while ((nRead = in.read(data, 0, data.length)) != -1) {
                    buffer.write(data, 0, nRead);
                }
                buffer.flush();
                b = buffer.toByteArray();
            }
        } else {
            // 处理本地路径
            b = Files.readAllBytes(Paths.get(path));
        }

        String base64 = Base64.getEncoder().encodeToString(b);
        if (urlEncode) {
            base64 = URLEncoder.encode(base64, "utf-8");
        }
        return base64;
    }
}
